package com.soft.line.filter;


import com.soft.line.util.redis.RedisClient;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


public class HttpRequestUtil {
    public static final RedisClient REDIS_SERVICE = (RedisClient) GlobalApplicationContextHolder.getApplicationContext()
            .getBean("redisClient");

    public static final String key = "SOFTLINE-BUILD";
    // 过期时间设置为 15 min
    public static final Integer expire = 60*15;

    public static UserTokenDto getUserToken() {

        final RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        final ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        final HttpServletRequest request = sra.getRequest();
        //HttpSession session=request.getSession();
        final Map<String, String> map = getHeadersInfo(request);
        String token = map.get("access-token");
        if (token == null || "".equals(token)) {
            token = request.getParameter("token");
        }
        final Token tokenInfo = new Token(token);
        String json = null;

        json = REDIS_SERVICE.getKeyValue(tokenInfo.getUsername());

        return GsonUtil.jsonToJavaBean(json);
    }

    private static Map<String, String> getHeadersInfo(final HttpServletRequest request) {
        final Map<String, String> map = new HashMap<String, String>();
        final Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String key = headerNames.nextElement();
            final String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
